#include "lightControl.h"

LightControl::LightControl(){

  light_Pin = LIGHT_PIN;
  switch_Pin = SWITCH_PIN;
  num_Leds = NUM_LEDS;
  brightness = BRIGHTNESS;

  leds = new CRGB[num_Leds];
  led_State = false;
  lastSwitch_State = HIGH; // 初始化开关未按下状态
  debounce_Delay = 50;     // 防抖动延时
}

void LightControl::setlight(){
  // 初始化LED
  FastLED.addLeds<WS2812, LIGHT_PIN, COLOR_ORDER>(leds, num_Leds).setCorrection(TypicalLEDStrip);
  FastLED.setBrightness(brightness);

  // 初始化开关引脚
  pinMode(switch_Pin, INPUT_PULLUP);
}

void LightControl::lightswitch()
{
  // 读取开关状态
  int switch_State = digitalRead(switch_Pin);

  // 若开关状态改变
  if (switch_State != lastSwitch_State)
  {
    // 延迟去抖动
    delay(debounce_Delay);
    // 再次读取开关状态
    switch_State = digitalRead(switch_Pin);
    // 开关状态确实改变
    if (switch_State != lastSwitch_State)
    {
      lastSwitch_State = switch_State;
      // 如果开关按下，切换LED状态
      if (switch_State == LOW)
      {
        led_State = !led_State; // 切换LED状态
        if (led_State)
        {
          // 打开LED，设置为白色
          for (int i = 0; i < num_Leds; i++)
          {
            leds[i] = CRGB::White;
          }
        }
        else
        {
          // 关闭LED，设置为黑色
          for (int i = 0; i < num_Leds; i++)
          {
            leds[i] = CRGB::Black;
          }
        }
        FastLED.show(); // 更新LED显示
      }
    }
  }
}

// 开启灯的函数
void LightControl::trunOn(){
  // 设置 LED 状态为打开
  led_State = true;
  // 设置 LED 为白色
  for (int i = 0; i < num_Leds; i++)
  {
    leds[i] = CRGB::White;
  }
  // 更新 LED 显示
  FastLED.show();
}

// 关闭灯的函数
void LightControl::trunOff(){
  // 设置 LED 状态为关闭
  led_State = false; // 设置所有 LED 为黑色（关闭）
  for (int i = 0; i < num_Leds; i++)
  {
    leds[i] = CRGB::Black;
  }
  // 更新 LED 显示
  FastLED.show();
}
